package br.com.me.ceap.down;

import br.com.me.ceap.BaseMojo;
import br.com.me.ceap.MECEAPUtils;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * Goal to download the Dynamic Objects and Document types mappings.
 *
 * @goal downloadMappingFiles
 * @requiresProject
 */
public class DownloadMappingFilesMojo extends BaseMojo {
// ------------------------------ FIELDS ------------------------------

    /**
     * Directory for Mapping files
     *
     * @parameter default-value="${basedir}/src/main/mapping"
     * @required
     */
    private File projectMappingDirectory;

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Mojo ---------------------

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        WebClient webClient = MECEAPUtils.forDownloadMappingJAR(this);

        this.getLog().info("Downloading CustomRoot mapping jar file");

        Attachment attachment = webClient.get(Attachment.class);

        this.getLog().debug("Downloaded CustomRoot mapping jar file");


        if (!projectMappingDirectory.exists()) {
            this.getLog().debug("Destiny directory doesn't exist. Creating " + projectMappingDirectory);
            if (!projectMappingDirectory.mkdirs())
                this.getLog().error("Error creating directory " + projectMappingDirectory);
        }


        try {
            JarInputStream jarInputStream = new JarInputStream(attachment.getDataHandler().getInputStream());

            boolean hasWrote = false;

            JarEntry jarEntry;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                String mappingFileName = projectMappingDirectory + File.separator + getParentFolder(jarEntry.getName()) + jarEntry.getName();

                File mappingFile = new File(mappingFileName);
                mappingFile.getParentFile().mkdirs();

                FileOutputStream fileOutputStream = new FileOutputStream(mappingFileName);
                IOUtils.copy(jarInputStream, fileOutputStream);
                fileOutputStream.close();

                this.getLog().info("Wrote " + mappingFileName);
                hasWrote = true;
            }

            if (!hasWrote)
                this.getLog().info("There are no Dynamic Objects or Document Types on CustomRoot");
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    private String getParentFolder(String fileName) {
        String fileParentPath = "";
        if (fileName.endsWith(".dom.xml")) {
            fileParentPath += "dataobject" + File.separator;
        } else if (fileName.endsWith(".ddm.xml")) {
            fileParentPath += "document" + File.separator;
        } else if (fileName.endsWith(".dsm.xml")) {
            fileParentPath += "datasource" + File.separator;
        } else if (fileName.endsWith(".dfm.xml")) {
            fileParentPath += "filter" + File.separator;
        } else if (fileName.endsWith(".gpm.xml")) {
            fileParentPath += "group" + File.separator;
        } else if (fileName.endsWith(".tmm.xml")) {
            fileParentPath += "templatemail" + File.separator;
        }
        return  fileParentPath.trim();
    }
}
